package Reflect.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: zcw
 * @version: 1.0
 * 通过反射机制创建实例
 */
@SuppressWarnings ({"all"})
public class ReflectCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //1. 获取User的class对象
        Class userClass = Class.forName ("Reflect.Test.User");
        //2. 通过public的无参构造器创建实例
        Object o = userClass.newInstance ();
        System.out.println (o);
        //3. 通过public的有参构造器创造实例
            //3.1 先得到对应构造器
        Constructor constructor = userClass.getConstructor (String.class);
            //3.2 创建实例，并传入实参
        Object o1 = constructor.newInstance ("雾已散声声慢");
        System.out.println (o1);
        //4. 通过非public的有参构造器
            // getConstructor只能返回public的构造器   getDeclaredConstructor能返回所有的
        Constructor constructor1 = userClass.getDeclaredConstructor (int.class, String.class);
        constructor1.setAccessible (true); //暴破。使用反射可以访问private构造器/方法/属性
        Object o2 = constructor1.newInstance (815, "Zzzzzzzzzzzz");
        System.out.println (o2);
    }
}
@SuppressWarnings ({"all"})
class User{
    private int age = 414;
    //赋初始值，效果更加明显
    private String name = "bcscb";

    public User() { //无参 public
    }

    public User(String name) { //public的有参构造器 增加对比
        this.name = name;
    }

    private User(int age, String name) { //有参 private
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
